package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.DamageListDao;
import com.atguigu.jxc.dao.DamageListGoodsDao;
import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.entity.DamageList;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.entity.vo.GoodsDamageVo;
import com.atguigu.jxc.service.DamageListGoodsService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DamageListGoodsServiceImpl
 * @Author 波
 * @Date 2024/9/24 21:20
 */
@Service
public class DamageListGoodsServiceImpl implements DamageListGoodsService {
    @Autowired
    private DamageListGoodsDao damageListGoodsDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private DamageListDao damageListDao;
    @Autowired
    private UserDao userDao;

    @Override
    @SneakyThrows
    @Transactional
    public void list(DamageList damageList, String damageListGoodsStr) {
        ObjectMapper objectMapper = new ObjectMapper();
        List<GoodsDamageVo> goodsDamageVoList = objectMapper.readValue(damageListGoodsStr, new TypeReference<List<GoodsDamageVo>>() {
        });
        Assert.notNull(goodsDamageVoList, "报损商品不能为空");
        damageList.setUserId(1);
        User user = userDao.getUserById(1);
        damageList.setTrueName(user.getUserName());
        //保存报损单
        damageListDao.save(damageList);
        DamageList damageList1 = damageListDao.getIdByDamageNumber(damageList.getDamageNumber());
        for (GoodsDamageVo goodsDamageVo : goodsDamageVoList) {
            //保存报损的商品信息
            damageListGoodsDao.save(goodsDamageVo, damageList1.getDamageListId());
            //减掉库存
            goodsDao.updateInventoryQuantity(goodsDamageVo.getGoodsNum(), goodsDamageVo.getGoodsId());
        }


    }

    @Override
    public Map<String, Object> damageListByTime(String sTime, String eTime) {
        HashMap<String, Object> map = new HashMap<>();
        List<DamageList> damageLists = damageListDao.damageListByTime(sTime, eTime);
        map.put("rows", damageLists);
        return map;
    }

    @Override
    public Map<String, Object> getGoodsList(Integer damageListId) {
        HashMap<String, Object> map = new HashMap<>();
        List<DamageListGoods> damageListGoods = damageListGoodsDao.getGoodsList(damageListId);
        map.put("rows", damageListGoods);
        return map;
    }
}
